/*
 * @Author: your name
 * @Date: 2020-09-22 17:23:28
 * @LastEditTime: 2021-02-01 18:15:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \longh_admin\src\utils\request.js
 */
import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { message } from 'ant-design-vue'

let development = process.env.NODE_ENV == 'development' ? true : false;
// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL: process.env.VUE_APP_API_BASE_URL,
  // 注释异步
  baseURL: development ? '/' : GolbUrl._BASE_URL_, // api 的 base_url
  // baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 30000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  console.log("这里")
  console.error(error)
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        // store.dispatch('Logout').then(() => {
        //   setTimeout(() => {
        //     window.location.reload()
        //   }, 1500)
        // })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  // const token = storage.get(ACCESS_TOKEN)   
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  // if (token) {
  //   config.headers['Authorization'] = token
  // }
  let _token = localStorage.getItem('Access-Token')
  config.headers['client_id'] = GolbUrl._clientId_
  config.headers['Authorization'] = 'gongxu_1'
  if (_token) {
    // config.headers['authorization-token'] = _token
    config.headers['Authorization'] = "Bearer " + _token.replace(/\"/g, "")
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  if (response.status === 200) {
    // if(response.data.code === 10004 || response.data.code === 40003) {
    //   message.warning('登录过期，请重新登录')
    //   localStorage.removeItem("Access-Token")
    //   localStorage.removeItem("LH_WEB_CODE")
    //   setTimeout(() => {
    //     const FULL_CHARTER = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopgrstuvwxyz"
    //     let state = ""
    //     for (let i = 0; i < 6; i++) {
    //       state += FULL_CHARTER[Math.floor(Math.random() * 52)]
    //     }
    //     window.location.href = GolbUrl.uaaUri + "/oauth/authorize?client_id=" + "&redirect_uri=" + "&response_type=code&state=" + state + '&userType=3'
    //   }, 1000)
    // }else {
    //   return Promise.resolve(response.data)
    // }
    //如果没有登录认证中心，先重定向前往认证中心登录界面
    // if (response.config.url.indexOf("/logout") != -1 && response.request.responseURL.indexOf("redirect_url") != -1) {
    //   //退出登录，重定向回认证中心
    //   location.href = response.request.responseURL;
    // } else if (response.request.responseURL && response.request.responseURL.indexOf("redirect_url") != -1) {
    //   let locationUrl = window.location.protocol + "//" + window.location.host;
    //   let url = response.request.responseURL.split("&");
    //   let redirectUrl = router.currentRoute.fullPath;
    //   let urlOne = url[0] + "&redirect_url=" + locationUrl + redirectUrl + "&" + url[url.length - 1];
    //   location.href = urlOne;
    // }
  } else {

    return Promise.reject(response.data);
  }


  return response.data
},
  // 服务器状态码不是2开头的的情况
  // 然后根据返回的状态码进行一些操作，例如登录过期提示，错误提示等等
  error => {
    console.log(error)
    if (error.response.status) {
      switch (error.response.status) {
        // 请求接口错误
        case 400:

          break;
        // 401: 未登录
        // 未登录则跳转登录页面，并携带当前页面的路径
        // 在登录成功后返回当前页面，这一步需要在登录页操作。
        case 401:

        // let redirectUrl = error.response.headers['redirect'];
        // if(redirectUrl.indexOf('auth/login') == -1){
        //   location.reload()
        // }else{
        //   location.href = redirectUrl
        // }
        // break;

        // 403 token过期
        // 登录过期对用户进行提示
        // 清除本地token和清空vuex中token对象
        // 跳转登录页面
        case 403:
          // 404请求不存在
          break;
        case 404:

          break;
        case 500:

          break;
        // 其他错误，直接抛出错误提示
        default:

      }
      return Promise.reject(error.response);
    }
  }
)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
